//
//  LockView.m
//  GestureUnlockDemo
//
//  Created by zhukaiqi on 16/8/25.
//  Copyright © 2016年 zhukaiqi. All rights reserved.
//

#import "LockView.h"

@interface LockView ()

/** 存储选中按扭的数组 */
@property (nonatomic,strong)NSMutableArray *selectedBtArray;

/** 手指所在的点 */
@property (nonatomic,assign)CGPoint fingerPoint;

@end

@implementation LockView


- (NSMutableArray *)selectedBtArray {

    if (!_selectedBtArray) {
        
        _selectedBtArray = [NSMutableArray array];
    }

    return _selectedBtArray;

}

- (void)awakeFromNib {

    [self initButton];

}

- (void)initButton {

    
    for (int  i = 0; i< 9; i++) {
        
        UIButton *bt = [UIButton buttonWithType:UIButtonTypeCustom];
        
        [bt setImage:[UIImage imageNamed:@"normal"] forState:UIControlStateNormal];
        
        [bt setImage:[UIImage imageNamed:@"select"] forState:UIControlStateSelected];
     
        //关闭button的交互,防止移动过程中拦截事件
        bt.userInteractionEnabled = NO;
        
        bt.tag = i+1000;
        
        [self addSubview:bt];
    }


}

- (void)layoutSubviews {

    [super layoutSubviews];
    
    //对子控件进行重新布局
    CGFloat btW = 60;
    
    CGFloat btH = btW;
    
    CGFloat marginX = (self.frame.size.width - 3*btW)/4;
    
    CGFloat marginY = marginX;
    
 
    for (int i= 0; i<self.subviews.count; i++) {
        
        NSInteger row = i/3;
        
        NSInteger column = i%3;
        
        UIButton *bt = self.subviews[i];
        
        
        bt.frame = CGRectMake(marginX+column*(marginX+btW), marginY+row*(marginY+btH), btW, btH);
    }

}

//点击时
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    [self changeBtSelectedStateWith:touches];
    
    
}

//移动时
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {

    
    [self changeBtSelectedStateWith:touches];
    
     self.fingerPoint = [self fetchCurrentTouchPointWith:touches];
    
    //重绘
    [self setNeedsDisplay];

}

//离开时
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    //取消按扭的选中状态
    //存储选中按扭的值
    NSString *str = @"";
    for (UIButton *bt in self.selectedBtArray) {
        
          bt.selected = NO;
        
        str = [str stringByAppendingString:[NSString stringWithFormat:@"%ld",bt.tag-1000]];
    }
   
    NSString *GPWD = [[NSUserDefaults standardUserDefaults] objectForKey:@"GPWD"];
    
    if (GPWD) {
        
          NSString *message = @"";
        if ([GPWD isEqualToString:str]) {
            
            message = @"密码正确";
        }
        else {
        
            message = @"密码错误";

        
        }
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        
        [alert show];
        
    }
    else {
        
      [[NSUserDefaults standardUserDefaults] setObject:str forKey:@"GPWD"];
    }
    
   
    //清除线
    [self.selectedBtArray removeAllObjects];
    
    [self setNeedsDisplay];

    

}
/**
 *  获取当前触摸点
 *
 *  @param touches
 *
 *  @return 当前触摸点
 */
- (CGPoint )fetchCurrentTouchPointWith:(NSSet<UITouch *> *)touches {


     UITouch *touch = touches.anyObject;
    
     return [touch locationInView:self];

}

/**
 *  获取bt,如果当前触摸点在bt上就返回bt
 *
 *  @param point 当前触摸点
 *
 *  @return bt
 */
- (UIButton *)fetchButtonContainsWith:(CGPoint)point {
    
     for (UIButton *bt in self.subviews) {
        
         //是否包含触摸点 如果包含返回bt
        if (CGRectContainsPoint(bt.frame, point)) {
            
            return bt;
        }
        
    }
    
    return nil;
    
}

/**
 *  改变bt的选中状态
 *
 *  @param touches 触摸集合
 */

- (void)changeBtSelectedStateWith:(NSSet <UITouch *> *)touches{


    CGPoint point = [self fetchCurrentTouchPointWith:touches];
    
    UIButton *bt = [self fetchButtonContainsWith:point];
    
    if (bt&&bt.selected==NO) {
        
        bt.selected = YES;
        
        [self.selectedBtArray addObject:bt];
    }
    

}

//绘制
- (void)drawRect:(CGRect)rect {

    //有bt时才绘制
    if (self.selectedBtArray.count) {
        
        
        UIBezierPath *path = [UIBezierPath bezierPath];
        
        for (int i = 0; i<self.selectedBtArray.count; i++) {
            
            
            UIButton *bt = self.selectedBtArray[i];
            
            //是第一个点
            if (i == 0) {
                
                //设置成路径的起点
                [path moveToPoint:bt.center];
            }
            else{
               // 不是第一个点画线
                [path addLineToPoint:bt.center];
            }
            
        }
        
        //给手指添加一条线
        [path addLineToPoint:self.fingerPoint];
        
        //线宽
         path.lineWidth = 6;
        
        //颜色
        [[UIColor whiteColor] set];
        
        //终点处理
        path.lineJoinStyle = kCGLineJoinRound;
        
        //连线
        [path stroke];
        

        
        
    }
    
    

}
@end
